package com.wmh.baseservice.skd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wmh.baseservice.common.service.TokenService;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.skd.pojo.SkdGoodsInfo;
import com.wmh.baseservice.skd.pojo.SkdGoodsSpec;
import com.wmh.baseservice.skd.pojo.SkdGroupBuyingActivities;
import com.wmh.baseservice.skd.pojo.SkdShoppingCart;
import com.wmh.baseservice.skd.pojo.vo.ShoppingCartRespVO;
import com.wmh.baseservice.skd.service.SkdGoodsInfoService;
import com.wmh.baseservice.skd.service.SkdGoodsSpecService;
import com.wmh.baseservice.skd.service.SkdGroupBuyingActivitiesService;
import com.wmh.baseservice.skd.service.SkdShoppingCartService;
import com.wmh.baseservice.skd.mapper.SkdShoppingCartMapper;
import com.wmh.baseservice.user.pojo.vo.UsInfoRespVO;
import com.wmh.baseservice.user.service.UsInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
* @author CH
* @description 针对表【skd_shopping_cart】的数据库操作Service实现
* @createDate 2024-01-15 14:54:58
*/
@Service
@Slf4j
public class SkdShoppingCartServiceImpl extends ServiceImpl<SkdShoppingCartMapper, SkdShoppingCart>
    implements SkdShoppingCartService{
    @Resource
    private TokenService tokenService;
    @Resource
    private UsInfoService usInfoService;
    @Resource
    private SkdShoppingCartMapper skdShoppingCartMapper;
    @Resource
    private SkdGroupBuyingActivitiesService skdGroupBuyingActivitiesService;
    @Resource
    private SkdGoodsInfoService skdGoodsInfoService;
    @Resource
    private SkdGoodsSpecService skdGoodsSpecService;

    /**
     * 添加商品到购物车
     * @param groupBuyingActivityId 团购活动id
     * @param goodsId 商品id
     * @param goodsSpecId 商品规格id
     * @return 返回是否添加成功信息
     */
    @Override
    public String addShoppingCart(Long groupBuyingActivityId, Long goodsId, Long goodsSpecId) {
        Long usId;
        try {
            // 根据token获取用户id
            usId = tokenService.getUserIdFromToken();
        } catch (IllegalStateException e) {
            log.error(e.getMessage());
            return ReturnBody.error("token异常!");
        }
        SkdGroupBuyingActivities groupBuyingActivity = skdGroupBuyingActivitiesService.getById(groupBuyingActivityId);
        log.info("groupBuyingActivity" + groupBuyingActivity);
        if (Objects.isNull(groupBuyingActivity) || groupBuyingActivity.getIsEnd() == 1) {
            return ReturnBody.error("该团购活动已删除或已结束, 请检查团购活动id是否正确!");
        }
        SkdGoodsInfo goods = skdGoodsInfoService.getById(goodsId);
        if (Objects.isNull(goods) || goods.getOffShelves() == 1) {
            return ReturnBody.error("该商品已删除或已下架, 请检查商品id是否正确!");
        }
        if (goodsSpecId != null) {
            SkdGoodsSpec skdGoodsSpec = skdGoodsSpecService.getById(goodsSpecId);
            if (Objects.isNull(skdGoodsSpec)){
                return ReturnBody.error("该商品规格不存在, 请检查商品规格id是否正确!");
            }
        }

        SkdShoppingCart shoppingCart = new SkdShoppingCart();
        shoppingCart.setUserId(usId)
                .setGroupBuyingActivityId(groupBuyingActivityId)
                .setGoodsId(goodsId)
                .setGoodsSpecId(Objects.isNull(goodsSpecId) ? null : goodsSpecId);
        skdShoppingCartMapper.insert(shoppingCart);
        return ReturnBody.success("添加成功!");
    }

    /**
     * 查看购物车商品列表
     * @return 返回购物车商品列表
     */
    @Override
    public String queryShoppingCartList(Long groupBuyingActivityId) {
        Long usId;
        try {
            // 根据token获取用户id
            usId = tokenService.getUserIdFromToken();
        } catch (IllegalStateException e) {
            log.error(e.getMessage());
            return ReturnBody.error("token异常!");
        }
        // 根据用户id获取用户头像和昵称
        UsInfoRespVO avatarAndNick = usInfoService.getAvatarAndNickByUsId(usId);

        QueryWrapper<SkdShoppingCart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", usId)
                .eq("off_shelves", 0)
                .eq(groupBuyingActivityId != null, "group_buying_activity_id", groupBuyingActivityId)
                .orderByDesc("create_time");

        List<SkdShoppingCart> skdShoppingCartList = skdShoppingCartMapper.selectList(queryWrapper);

        List<ShoppingCartRespVO> shoppingCartRespVOList = new ArrayList<>();

        skdShoppingCartList.forEach( sc -> {
            ShoppingCartRespVO shoppingCartRespVO = new ShoppingCartRespVO();
            // 根据团购活动id获取团购信息
            SkdGroupBuyingActivities skdGroupBuyingActivities = skdGroupBuyingActivitiesService.getById(sc.getGroupBuyingActivityId());
            // 根据商品规格id获取商品规格名
            String desc = null;
            String goodsImageUrl = null;
            BigDecimal goodsPrice = null;
            if (!Objects.isNull(sc.getGoodsSpecId())) {
                desc = skdGoodsSpecService.getDescById(sc.getGoodsSpecId());
                // 获取商品规格图像地址
                goodsImageUrl = skdGoodsSpecService.getGoodsImageUrlById(sc.getGoodsSpecId());
                // 获取商品规格价格
                goodsPrice = skdGoodsSpecService.getGoodsPriceById(sc.getGoodsSpecId());
            }
            // 如果没有商品规格图像则获取首张商品图像
            if (Objects.isNull(goodsImageUrl)) {
                goodsImageUrl = skdGoodsInfoService.getGoodsImageUrlById(sc.getGoodsId());
            }
            // 如果是无规格商品则获取无规格商品价格
            if (Objects.isNull(goodsPrice)) {
                goodsPrice = skdGoodsInfoService.getGoodsPriceById(sc.getGoodsId());
            }

            shoppingCartRespVO.setShoppingCartId(sc.getId())
                    .setUserNick(avatarAndNick.getNick())
                    .setUserAvatarUrl(avatarAndNick.getAvatar())
                    .setGroupBuyingActivityId(skdGroupBuyingActivities.getId())
                    .setGroupBuyingActivityTitle(skdGroupBuyingActivities.getTitle())
                    // 解析商品快照获取指定商品名称
                    .setGoodsName(skdGroupBuyingActivitiesService.getGoodsNameFromGoodsSnapshot(skdGroupBuyingActivities.getGoodsSnapshot(), sc.getGoodsId()))
                    .setGoodsSpec(desc)
                    .setGoodsImageUrl(goodsImageUrl)
                    .setGoodsPrice(goodsPrice)
                    .setCrossedPrice(skdGroupBuyingActivitiesService.getCrossedPriceFromGoodsSnapshot(skdGroupBuyingActivities.getGoodsSnapshot(), sc.getGoodsId()))
                    .setGoodsNum(sc.getQuantity());

            shoppingCartRespVOList.add(shoppingCartRespVO);
        });
        return ReturnBody.success(shoppingCartRespVOList);
    }

    @Override
    public String getOffShelvesGoodsList() {
        Long usId;
        try {
            // 根据token获取用户id
            usId = tokenService.getUserIdFromToken();
        } catch (IllegalStateException e) {
            log.error(e.getMessage());
            return ReturnBody.error("token异常!");
        }
        // 根据用户id获取用户头像和昵称
        UsInfoRespVO avatarAndNick = usInfoService.getAvatarAndNickByUsId(usId);

        QueryWrapper<SkdShoppingCart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", usId).eq("off_shelves", 1);
        List<SkdShoppingCart> list = skdShoppingCartMapper.selectList(queryWrapper);

        List<ShoppingCartRespVO> shoppingCartRespVOList = new ArrayList<>();

        list.forEach(i -> {
            ShoppingCartRespVO shoppingCartRespVO = new ShoppingCartRespVO();
            // 根据团购活动id获取团购信息
            SkdGroupBuyingActivities skdGroupBuyingActivities = skdGroupBuyingActivitiesService.getById(i.getGroupBuyingActivityId());
            // 根据商品规格id获取商品规格名
            String desc = null;
            String goodsImageUrl = null;
            BigDecimal goodsPrice = null;
            if (!Objects.isNull(i.getGoodsSpecId())) {
                desc = skdGoodsSpecService.getDescById(i.getGoodsSpecId());
                // 获取商品规格图像地址
                goodsImageUrl = skdGoodsSpecService.getGoodsImageUrlById(i.getGoodsSpecId());
                // 获取商品规格价格
                goodsPrice = skdGoodsSpecService.getGoodsPriceById(i.getGoodsSpecId());
            }
            // 如果没有商品规格图像则获取首张商品图像
            if (Objects.isNull(goodsImageUrl)) {
                goodsImageUrl = skdGoodsInfoService.getGoodsImageUrlById(i.getGoodsId());
            }
            // 如果是无规格商品则获取无规格商品价格
            if (Objects.isNull(goodsPrice)) {
                goodsPrice = skdGoodsInfoService.getGoodsPriceById(i.getGoodsId());
            }

            shoppingCartRespVO.setShoppingCartId(i.getId())
                    .setUserNick(avatarAndNick.getNick())
                    .setUserAvatarUrl(avatarAndNick.getAvatar())
                    .setGroupBuyingActivityId(skdGroupBuyingActivities.getId())
                    .setGroupBuyingActivityTitle(skdGroupBuyingActivities.getTitle())
                    // 解析商品快照获取指定商品名称
                    .setGoodsName(skdGroupBuyingActivitiesService.getGoodsNameFromGoodsSnapshot(skdGroupBuyingActivities.getGoodsSnapshot(), i.getGoodsId()))
                    .setGoodsSpec(desc)
                    .setGoodsImageUrl(goodsImageUrl)
                    .setGoodsPrice(goodsPrice)
                    .setCrossedPrice(skdGroupBuyingActivitiesService.getCrossedPriceFromGoodsSnapshot(skdGroupBuyingActivities.getGoodsSnapshot(), i.getGoodsId()));

            shoppingCartRespVOList.add(shoppingCartRespVO);
        });
        return ReturnBody.success(shoppingCartRespVOList);
    }

    /**
     * 获取用户失效商品id
     * @param usId 用户id
     * @return 返回失效商品id列表
     */
    @Override
    public List<Long> getInvalidGoodsIds(Long usId) {
        return skdShoppingCartMapper.getInvalidGoodsIds(usId);
    }

    /**
     * 根据用户id和团购活动下架购物车商品
     * @param groupBuyingActivityId 团购活动id
     * @return 返回是否下架成功
     */
    @Override
    public boolean offShelvesShoppingCart(Long groupBuyingActivityId) {
        return skdShoppingCartMapper.offShelvesShoppingCart(groupBuyingActivityId);
    }

    /**
     * 根据用户id和团购活动id上架购物车商品
     * @param groupBuyingActivityId 团购活动id
     * @return 返回是否上架成功
     */
    @Override
    public boolean onShelvesShoppingCart(Long groupBuyingActivityId) {
        return skdShoppingCartMapper.onShelvesShoppingCart(groupBuyingActivityId);
    }
}




